package designpattern.singeleton;

/**
 * 解决懒汉式单例的线程安全问题
 */
public class SingletonLazyDemo2 {
    public static void main(String[] args) {
        System.out.println(NewBand.getInstance()==NewBand.getInstance());
    }
}
class NewBand{
    //1.私有化构造器
    private NewBand(){

    }
    //2.创建给外部使用的唯一实例
    //先声明，不初始化
    private static NewBand Instance = null;

//    public static synchronized NewBand getInstance() { //解决方式一，同步方法
    public static  NewBand getInstance() {
//        解决方式二:同步块，用类对象锁住，等同于方式一，效率较差，
//        synchronized(NewBand.class) {
//            if (Instance == null) {
//                Instance = new NewBand();
//            }
//        }
        //解决方式三，先判断再嵌套同步块，效率更高
        if(Instance == null) {
            synchronized (NewBand.class) {
                if (Instance == null) {
                    Instance = new NewBand();
                }
            }
        }
        return Instance;
    }
}
